package com.hsc.www.reSend.core;

import com.hsc.www.reSend.RabbitTemplateExtend;
import com.hsc.www.reSend.core.delayedQueue.CapillaryDelayedQueue;
import com.hsc.www.reSend.core.delayedQueue.CapillaryDelayedQueueFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class Config {


    public static final String DELAYED_MESSAGE_REGISTRAR_QUEUE = "cds_delayed_message_registrar_queue";

    public static final String DELAYED_MESSAGE_RELIVE_QUEUE = "cds_delayed_message_relive_queue";


    // 延迟消息注册队列
    @Bean(name = DELAYED_MESSAGE_REGISTRAR_QUEUE)
    public Queue delayedMessageRegistrarQueue() {
        return new Queue(DELAYED_MESSAGE_REGISTRAR_QUEUE, true, false, false);
    }

    // 延迟消息复活队列
    @Bean(name = DELAYED_MESSAGE_RELIVE_QUEUE)
    public Queue delayedMessageReliveQueue() {
        return new Queue(DELAYED_MESSAGE_RELIVE_QUEUE, true, false, false);
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);// 只有设置为 true，spring 才会加载 RabbitAdmin 这个类
        return rabbitAdmin;
    }

    @Bean
    public RabbitTemplateExtend rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplateExtend rabbitTemplate = new RabbitTemplateExtend(connectionFactory);
        return rabbitTemplate;
    }

    @Autowired
    public void createCapillaryDelayedQueues(RabbitAdmin rabbitAdmin, CapillaryDelayedQueueFactory capillaryDelayedQueueFactory) {
        for (CapillaryDelayedQueue queueInfo : capillaryDelayedQueueFactory.totalQueues()) {
            Queue queue = this.doCreateCapillaryDelayedQueues(queueInfo);
            rabbitAdmin.declareQueue(queue);
        }
    }

    private Queue doCreateCapillaryDelayedQueues(CapillaryDelayedQueue queueInfo) {
        Map args = new HashMap<String, Object>() {{
            put("x-dead-letter-exchange", "");
            put("x-dead-letter-routing-key", DELAYED_MESSAGE_RELIVE_QUEUE);
            put("x-message-ttl", queueInfo.getTimeUnit().toMillis(queueInfo.getDelayedTime()));
        }};
        return new Queue(queueInfo.getDelayedQueueName(), true, false, true, args);
    }


}